package com.chenyq.rabbitmq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;



/**
 *
 * @author chenyq
 * @date 2023/11/28
 */

public class Producer {

    private static final String TOPIC_EXCHANGE = "topicExchange";
    private static final String TOPIC_QUEUE_1 = "topicQueue_1";
    private static final String TOPIC_QUEUE_2 = "topicQueue_2";

    public static void main(String[] args) {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置主机地址
        factory.setHost("127.0.0.1");
        // 设置端口号
        factory.setPort(5672);
        // 设置虚拟主机
        factory.setVirtualHost("/");
        // 设置用户名
        factory.setUsername("admin");
        // 设置密码
        factory.setPassword("123456");
        // 创建连接
        Connection connection = null;
        // 创建通道
        Channel channel = null;
        try {
            // 创建连接
            connection = factory.newConnection();
            // 创建通道
            channel = connection.createChannel();
            //声明交换机
            channel.exchangeDeclare(TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC,true,false,null);
            // 声明队列
            channel.queueDeclare(TOPIC_QUEUE_1, true, false, false, null);
            channel.queueDeclare(TOPIC_QUEUE_2, true, false, false, null);

            channel.queueBind(TOPIC_QUEUE_1,TOPIC_EXCHANGE,"chenyq.beijing.*.*");//我是北京校区的校长;
            channel.queueBind(TOPIC_QUEUE_2,TOPIC_EXCHANGE,"chenyq.nanjing.caiwubu.*");//我是南京校区的财务部长;

                String msg1 = "目前减员两位";
                // 发布消息
                channel.basicPublish(TOPIC_EXCHANGE,"chenyq.beijing.renshibu.info",null,msg1.getBytes());

                String msg2 = "资金减为50%";
                channel.basicPublish(TOPIC_EXCHANGE,"chenyq.nanjing.caiwubu.error",null,msg2.getBytes());

                String msg3 = "受人员影响，全体员工工资减少10%";
                channel.basicPublish(TOPIC_EXCHANGE,"chenyq.beijing.caiwubu.warning",null,msg3.getBytes());


        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                // 关闭通道
                if (channel != null & connection != null) {
                    channel.close();
                    connection.close();
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    }


}
